using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml.Serialization;

namespace HighFantasyRPG
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        
        SpriteFont font;
        public List<Level> levels = new List<Level>();
        private Level currentlevel;
        
        public int levelIndex, numberofLevels;
        private DirectoryInfo directory;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 600;
            IsMouseVisible = true;
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            font = Content.Load<SpriteFont>("Fonts/Hud");
            
            LoadLevels();
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            if (currentlevel.Exitreached == true)
            {

                if (currentlevel.levelIndex >= levels.Count)
                currentlevel = levels[0];
                else

                currentlevel = levels[currentlevel.levelIndex + 1];
                currentlevel.Exitreached = false;
            }
            else
                currentlevel.Update(gameTime);

            base.Update(gameTime);
        }

        private void HandleInput()
        {
            // get all of our input states
            

            


        }

        

        private void LoadLevels()
        {

            string path = Content.RootDirectory + "/Maps/";
            directory = new DirectoryInfo(path);

            foreach (FileInfo file in directory.GetFiles())
            {

             if (file.Name.Contains(".xml"))
                 {
             numberofLevels += 1;
               
            // move to the next level
            levelIndex = (levelIndex + 1) % numberofLevels;

            Stream stream = File.Open(path + file.Name, FileMode.Open);
            StreamReader txtreader = new StreamReader(stream);

            levels.Add(new Level(file.Name, stream, Int32.Parse(Path.GetFileNameWithoutExtension(file.Name)), Content));

            currentlevel = levels[0];
                }
            }
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            
            Matrix cameraTransform = Matrix.CreateTranslation(new Vector3(-currentlevel.cameraPosition, 0));

                
            spriteBatch.Begin(SpriteSortMode.Deferred,
                  BlendState.AlphaBlend,
                  null, null, null, null,
                  cameraTransform);
            
            GraphicsDevice.Clear(Color.Black);


            currentlevel.Draw(gameTime, spriteBatch);
            


            spriteBatch.DrawString(font, "PlayerXY=" + currentlevel.player.CoordX + "  " + currentlevel.player.CoordY + " " + currentlevel.GetCollision(currentlevel.player.CoordX, currentlevel.player.CoordY) + " " + currentlevel.player.collision.Type, new Vector2(0, 0), Color.White);
            spriteBatch.DrawString(font, "PlayerData=" + currentlevel.player.data.Profile.Name + " " + currentlevel.player.data.Profile.Profession, new Vector2(0, 20), Color.White);
            spriteBatch.DrawString(font, "Accel=" + currentlevel.player.movement.ToString(), new Vector2(0, 40), Color.White);
            spriteBatch.DrawString(font, "Object=" + currentlevel.objects[0].localBounds.X + " " + currentlevel.objects[0].localBounds.Y, new Vector2(0, 60), Color.White);
            spriteBatch.DrawString(font, "Level=" + currentlevel.Height + " " + currentlevel.Width + " " + currentlevel.mapfile.Name, new Vector2(0, 80), Color.White);
            spriteBatch.DrawString(font, "Camera=" + currentlevel.cameraPositionX + " " + currentlevel.cameraPositionY, new Vector2(0, 100), Color.White);
            spriteBatch.DrawString(font, "Entity=" + currentlevel.messagebox.counter + " " + currentlevel.messagebox.time  + " " + currentlevel.messagebox.isVisible, new Vector2(0, 120), Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
